<template>
  <div class="booksBox">
    <div class="header">
      <div>
        <i class="el-icon-refresh-left" @click="recover"></i>
        <el-button type="primary" @click="add" style="margin-left: 10px"
          >添加</el-button
        >
      </div>

      <div class="search">
        <el-input
          style="width: 75%"
          v-model="content"
          @keyup.native.enter="search"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="search"
          >搜索</el-button
        >
      </div>
    </div>

    <el-table style="width: 100%" :data="booksData">
      <el-table-column type="index" label="序号" width="100">
        <!-- <slot slot-scope="{ $index }">{{ $index + 1 }}</slot> -->
      </el-table-column>
      <el-table-column prop="title" label="书名"> </el-table-column>
      <el-table-column label="封面图">
        <slot slot-scope="{ row }">
          <div class="demo-image__preview">
            <el-image
              style="width: 50px; height: 50px"
              :src="row.picture ? 'http://127.0.0.1:5000/' + row.picture : ''"
              :preview-src-list="[
                row.picture ? 'http://127.0.0.1:5000/' + row.picture : '',
              ]"
            >
              <div
                slot="error"
                class="image-slot"
                style="display: flex; justify-content: center"
              >
                <i class="el-icon-picture-outline"></i>
              </div>
              ></el-image
            >
          </div>
        </slot>
      </el-table-column>
      <el-table-column label="所属分类">
        <slot slot-scope="{ row }">{{
          row.cate_id ? row.BooksType.name : "暂无分类"
        }}</slot>
      </el-table-column>
      <el-table-column label="操作">
        <slot slot-scope="{ row }">
          <el-button
            type="warning"
            icon="el-icon-view"
            circle
            @click="particulars(row.content)"
          ></el-button>
          <el-button
            type="info"
            icon="el-icon-edit"
            circle
            @click="edit(row.id)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="del(row)"
          ></el-button>
        </slot>
      </el-table-column>
    </el-table>

    <div class="footer">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="count"
        :page-size="pageSize"
        @current-change="jump"
        :current-page.sync="pageNum"
      >
      </el-pagination>
    </div>
    <!-- 添加页面 -->

    <el-dialog
      title="添加"
      :visible.sync="dialogVisible1"
      width="40%"
      :before-close="handleClose1"
      :close-on-click-modal="false"
      v-if="dialogVisible1"
    >
      <el-form
        status-icon
        label-width="100px"
        class="demo-ruleForm"
        :model="addBookData"
        ref="form"
      >
        <el-form-item label="书名" prop="title">
          <el-input
            type="text"
            autocomplete="off"
            style="width: 70%"
            v-model="addBookData.title"
            name="addBookData.title"
          ></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            autocomplete="off"
            style="width: 70%"
            v-model="addBookData.content"
            name="addBookData.content"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属分类" prop="bookType">
          <el-select
            placeholder="请选择书籍分类"
            v-model="addBookData.bookType"
            name="addBookData.bookType"
          >
            <el-option
              v-for="item in typeData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图">
          <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:5000/addpicture"
            :data="{ uploadsUrl: addBookData.uploadsUrl }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            name="cover"
          >
            <div class="el-upload">
              <img v-if="cover" :src="cover" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmAdd">添 加</el-button>
        <el-button @click="cancelAdd">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 编辑页面 -->
    <el-dialog
      title="编辑"
      :visible.sync="dialogVisible2"
      width="40%"
      :before-close="handleClose2"
      :close-on-click-modal="false"
    >
      <el-form
        status-icon
        label-width="100px"
        class="demo-ruleForm"
        :model="editBookData"
      >
        <el-form-item label="书名" prop="title">
          <el-input
            type="text"
            autocomplete="off"
            style="width: 70%"
            v-model="editBookData.title"
          ></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            autocomplete="off"
            style="width: 70%"
            v-model="editBookData.content"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属分类" prop="bookType">
          <el-select v-model="editBookData.bookType">
            <el-option
              v-for="item in typeData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图">
          <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:5000/editpicture"
            :data="{ uploadsUrl: editBookData.uploadsUrl }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess2"
            :before-upload="beforeAvatarUpload"
            name="cover2"
          >
            <!-- 回显图片 -->
            <div class="el-upload">
              <i
                v-if="!editBookData.uploadsUrl"
                class="el-icon-plus avatar-uploader-icon"
              ></i>
              <img
                v-if="!cover2 && editBookData.uploadsUrl"
                :src="
                  editBookData.uploadsUrl
                    ? 'http://127.0.0.1:5000/' + editBookData.uploadsUrl
                    : ''
                "
                class="avatar"
              />
              <img v-if="cover2" :src="cover2" class="avatar" />
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
        <el-button @click="cancelEdit">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import axios from "axios";
import {
  getType,
  search,
  confirmAdd,
  edit,
  confirmEdit,
  del,
  paging,
  cancel,
} from "@/api/";
export default {
  data() {
    return {
      count: 0,
      pageSize: 5,
      booksData: [],
      content: "",
      addBookData: {
        title: "",
        content: "",
        bookType: "",
        uploadsUrl: "",
      },
      typeData: [],
      editBookData: {
        id: 0,
        title: "",
        content: "",
        bookType: "",
        uploadsUrl: "",
      },
      dialogVisible1: false,
      dialogVisible2: false,
      pageNum: 1,
      cover: "",
      cover2: "",
    };
  },
  methods: {
    // 刷新
    recover() {
      this.pageNum = 1;
      this.paging(1);
    },
    // 搜索
    async search() {
      if (!this.content.trim()) {
        this.$message({
          message: "搜索内容不能为空",
          type: "warning",
        });
        this.content = "";
        return;
      }
      let { data } = await search(this.content);
      this.booksData = data;
      this.count = data.length;
      this.content = "";
    },
    // 获取所有书籍类型
    async getType() {
      let { data } = await getType();
      this.typeData = data;
    },
    // 查看详情
    particulars(content) {
      this.$alert(`${content}`, "详情", {
        confirmButtonText: "确定",
        callback: (action) => {},
      });
    },
    // 添加页面
    add() {
      this.dialogVisible1 = true;
      this.getType();
    },
    handleClose1(done) {
      done();
      cancel();
      // this.$refs.form.resetFields();
      this.addBookData = {};
      this.cover = "";
    },
    // 添加操作
    async confirmAdd() {
      this.dialogVisible1 = false;

      let { data } = await confirmAdd({
        title: this.addBookData.title,
        content: this.addBookData.content,
        cateId: this.addBookData.bookType,
        picture: this.addBookData.uploadsUrl,
      });
      let { code, message } = data;
      if (code === 20000) {
        this.$message({
          message,
          type: "success",
        });
      } else {
        this.$message.error(message);
      }
      this.paging(this.pageNum);
      this.addBookData = {};
      this.cover = "";
    },
    // 取消添加
    cancelAdd() {
      this.dialogVisible1 = false;
      this.addBookData = {};
      this.cover = "";
      cancel();
    },
    // 编辑页面
    async edit(id) {
      this.cover2 = "";
      this.dialogVisible2 = true;
      let { data } = await edit(id);
      this.getType();
      this.editBookData.id = data.id;
      this.editBookData.title = data.title;
      this.editBookData.content = data.content;
      this.editBookData.bookType = data.cate_id ? data.cate_id : "暂无分类";
      this.editBookData.uploadsUrl = data.picture;
      // console.log();
    },
    handleClose2(done) {
      done();
      cancel();
    },
    // 编辑操作
    async confirmEdit() {
      this.dialogVisible2 = false;
      this.cover2 = "";
      let { data } = await confirmEdit(this.editBookData.id, {
        title: this.editBookData.title,
        content: this.editBookData.content,
        cateId: this.editBookData.bookType,
        picture: this.editBookData.uploadsUrl,
      });
      let { code, message } = data;
      if (code === 20000) {
        this.$message({
          message,
          type: "success",
        });
      } else {
        this.$message.error(message);
      }
      this.paging(this.pageNum);
    },
    // 取消编辑
    cancelEdit() {
      this.dialogVisible2 = false;
      cancel();
    },
    // 删除操作
    del(book) {
      let id = book.id;
      let title = book.title;
      this.$confirm(`你确定要删除《${title}》吗`, "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (this.booksData.length === 1) {
            this.pageNum -= 1;
          }
          let { data } = await del(id);
          let { code, message } = data;
          if (code === 20000) {
            this.$message({
              message,
              type: "success",
            });
          } else {
            this.$message.error(message);
          }

          this.paging(this.pageNum);
        })
        .catch(() => {});
    },
    // 封装一个分页跳转函数
    async paging(page) {
      let { data } = await paging(page, this.pageSize);
      let { rows, totalCount } = data;
      this.booksData = rows;
      this.count = totalCount;
    },
    // 分页操作
    jump(...args) {
      this.pageNum = args[0];
      this.paging(args[0]);
    },
    async handleAvatarSuccess(res, file) {
      // 预览
      console.log("handleAvatarSuccess", res);
      this.cover = URL.createObjectURL(file.raw);
      this.addBookData.uploadsUrl = res;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    async handleAvatarSuccess2(res, file) {
      // 预览
      this.cover2 = URL.createObjectURL(file.raw);
      this.editBookData.uploadsUrl = res;
    },
  },
  mounted() {
    // 挂载时默认调用一次
    this.paging(1);
  },
};
</script>

<style lang="scss" scoped>
.booksBox {
  width: 98%;
  min-height: 100%;
  // border: 1px solid #ccc;
  position: relative;

  .header {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;

    .search {
      width: 40%;
      display: flex;
      justify-content: space-between;
    }
  }
  .footer {
    position: absolute;
    width: 100%;
    bottom: 0;
    text-align: center;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>